<?php
/**
 * Project: Recipe
 * File: UserAction.class.php
 * Author: Xnfy520@gmail.com
 * Date: 12-4-16
 * Time: 上午10:33
 */

	class UserAction extends CommonAction{

		function index(){
			import("ORG.Util.Page");
			$user = D('UserView');

			if(isset($_POST['search'])){
				if(!empty($_POST['key'])){
					switch($_POST['search']){
						case 1 :
							$datas['id'] = $_POST['key'];
							break;
						case 2:
							$datas['username'] = array("like","%{$_POST['key']}%");
							break;
						case 3 :
							$datas['email'] = array('like',"%{$_POST['key']}%");
							break;
					}

					$total = $user->where($datas)->count();
					$Page = new Page($total, C('PAGENUM'));
					$list = $user->where($datas)->limit($Page->firstRow.','.$Page->listRows)->order('id desc')->select();

					$show = $Page->show();

				}else{
					$this->error('搜索内容不能为空');
				}
			}else{
				if(isset($_GET['rid'])){
					$total = $user->where('roleid='.$_GET['rid'])->count();
					$Page = new Page($total, C('PAGENUM'));// 实例化分页类 传入总记录数和每页显示的记录数
					$list = $user->where('roleid='.$_GET['rid'])->limit($Page->firstRow.','.$Page->listRows)->order('id desc')->select();
				}else{
					$total = $user->count();
					$Page = new Page($total, C('PAGENUM'));// 实例化分页类 传入总记录数和每页显示的记录数
					$list = $user->limit($Page->firstRow.','.$Page->listRows)->order('id desc')->select();
				}

				$show = $Page->show();// 分页显示输出
			}

			$role = M('Role');
			$roleinfo = $role->field('id,name')->where('publish=1')->select();
			$this->assign('roleinfo', $roleinfo);
			$this->assign('list',$list);// 赋值数据集
			$this->assign('show',$show);// 赋值分页输出
			$this->display('index');
		}

		/**
		 * 指向添加用户界面
		 */
		function add(){
			$role = M('Role');
			$roleinfo = $role->field('id,name')->where('publish=1')->order('id')->select();
			if(empty($roleinfo)){
				$this->error('请先创建用户分组',__APP__.'/Role/add');
			}else{
				$this->assign('roleinfo', $roleinfo);
				$this->display();
			}
		}

		/**
		 * 添加用户
		 */
		function insert(){
			$user = D('User');
			$tmpdir = './Public/Content/tmp/';
			$srcdir = './Public/Content/User/';

						if($data = $user->create()){
							if($data['status']==0){
								$data['uniqid'] = md5(time());
							}
							$roleuser = M('RoleUser');
							$role = M('Role');
							$data['exp'] = $role->where('id='.$_POST['roleid'])->getField('needexp');

								if($userid = $user->add($data)){
									if(!empty($data['gravatar'])){
										copy($tmpdir.$data['gravatar'], $srcdir.$data['gravatar']);
										if($dirsrc = opendir($tmpdir)){
											while($files = readdir($dirsrc)){
												if($files!='.' && $files!='..'){
													$pathfile = $tmpdir.$files;
													if(is_file($pathfile)){
														unlink($pathfile);
													}
												}
											}
										}
									}
									$roleuserdata['roleid'] = $_POST['roleid'];
									$roleuserdata['userid'] = $userid;
									$roleuser->add($roleuserdata);

									if(C('ENABLE')==1){

										import("ORG.Net.phpmailer");
										$mail = new PHPMailer(true);
										$mail->IsSMTP();
										$mail->SMTPAuth   = true;
										$mail->Port       = C('EMAILPORT');
										$mail->Host       =C('EMAILSERVER');
										$mail->Username   = C('FROMEMAIL');
										$mail->Password   = C('PASSWORD');
										$mail->AddReplyTo(C('FROMEMAIL'),C('FROMEMAILALIAS'));
										$mail->From       = C('FROMEMAIL');
										$mail->FromName   = C('FROMEMAILALIAS');
										$mail->IsHTML(true);
										$mail->AddAddress($data['email']);

										$setmail = M('SetEmail');

										if($data['status']==0){
											$activemail = $setmail->find(1);
											if($activemail['status']==1){
												$mail->Subject  = $activemail['title'];
												$body = str_replace('%username%', $data['username'], $activemail['content']);
												$body = str_replace('%activeurl%', 'http://www.meishij.com/User/active/action/ok/uniqid/'.$data['uniqid'], $body);
												$body = str_replace('%date%', date('Y-m-d H:i:s'), $body);
											}
										}else{
											$successmail = $setmail->find(2);
											if($successmail['status']==1){
												$mail->Subject  = $successmail['title'];
												$body = str_replace('%username%', $data['username'], $successmail['content']);
												$body = str_replace('%date%', date('Y-m-d H:i:s'), $body);
											}
										}
										$mail->MsgHTML($body);
										$mail->Send();
									}
									$this->success('添加用户成功', __APP__.'/User/index');
								}else{
									  $this->error('添加用户失败');
								}
						}else{
								$this->error($user->getError(), __APP__.'/User/add');
						}
		}

		/**
		 * 指向修改用户界面
		 */
		function edit(){
			if(isset($_GET['id']) && !empty($_GET['id'])){
				$user = D('User');
				$data = $user->relation(true)->find($_GET['id']);
				$this->assign('data', $data);
				$role = M('Role');
				$roleinfo = $role->field('id,name')->where('publish=1')->select();
				$this->assign('roleinfo', $roleinfo);
				$this->display();
			}else{
				$this->error('异常操作');
			}
		}

		/**
		 *用户头像上传
		 */
		function uploads(){
			import("ORG.Net.emit_upload");
			import("ORG.Util.emit_image");
			$upload = new upload(array("filepath"=>"./Public/Content/tmp","allowtype"=>array('gif','png','jpg'),"israndname"=>true,"maxsize"=>2000000));
			if($upload->uploadfiles('pic')){
				$img = new image("./Public/Content/tmp");
				$imgname =  $upload->getnewname();
				if($img->cut($imgname)){
					$img->thumb($imgname, 70, 70);
				}
				echo $upload->getnewname();
			}else{
				echo $upload->geterrormsg();
			}
		}


		/**
		 * 修改用户信息
		 */
		function update(){
			if(isset($_POST['id']) && !empty($_POST['id'])){
				$tmpdir = './Public/Content/tmp/';
				$srcdir = './Public/Content/User/';

				$user = M('User');
				$userinfo = $user->find($_POST['id']);

					if($data = $user->create()){

						$roleuser = M('RoleUser');
						$datas['roleid'] = $_POST['roleid'];

						if($roleuser->where('userid='.$userinfo['id'])->save($datas)){
							$role = M('Role');
							$data['exp'] = $role->where('id='.$_POST['roleid'])->getField('needexp');
						}

						if($data['status']==0){
							$data['uniqid'] = md5(time());
						}else{
							$data['uniqid'] = '';
						}

						if(empty($data['password'])){

							unset($data['password']);
								$user->save($data);
									if($data['gravatar']!=$userinfo['gravatar']){
										unlink($srcdir.$userinfo['gravatar']);
										copy($tmpdir.$data['gravatar'], $srcdir.$data['gravatar']);
										if($dirsrc = opendir($tmpdir)){
											while($files = readdir($dirsrc)){
												if($files!='.' && $files!='..'){
													$pathfile = $tmpdir.$files;
													if(is_file($pathfile)){
														unlink($pathfile);
													}
												}
											}
										}
									}

						}else{

							$data['password'] = md5($data['password']);
							$user->save($data);
								if($data['gravatar']!=$userinfo['gravatar']){
									unlink($srcdir.$userinfo['gravatar']);
									copy($tmpdir.$data['gravatar'], $srcdir.$data['gravatar']);
									if($dirsrc = opendir($tmpdir)){
										while($files = readdir($dirsrc)){
											if($files!='.' && $files!='..'){
												$pathfile = $tmpdir.$files;
												if(is_file($pathfile)){
													unlink($pathfile);
												}
											}
										}
									}
								}
						}

						if($userinfo['status']!=$data['status']){

							if(C('ENABLE')==1){

								import("ORG.Net.phpmailer");
								$mail = new PHPMailer(true);
								$mail->IsSMTP();
								$mail->SMTPAuth   = true;
								$mail->Port       = C('EMAILPORT');
								$mail->Host       =C('EMAILSERVER');
								$mail->Username   = C('FROMEMAIL');
								$mail->Password   = C('PASSWORD');
								$mail->AddReplyTo(C('FROMEMAIL'),C('FROMEMAILALIAS'));
								$mail->From       = C('FROMEMAIL');
								$mail->FromName   = C('FROMEMAILALIAS');
								$mail->IsHTML(true);
								$mail->AddAddress($_POST['sendemail']);

								$setmail = M('SetEmail');

								if($data['status']==0){
									$activemail = $setmail->find(1);
									if($activemail['status']==1){
										$mail->Subject  = $activemail['title'];
										$body = str_replace('%username%', $_POST['sendusername'], $activemail['content']);
										$body = str_replace('%activeurl%', 'http://www.meishij.com/User/active/action/ok/uniqid/'.$data['uniqid'], $body);
										$body = str_replace('%date%', date('Y-m-d H:i:s'), $body);
									}
								}else{
									$successmail = $setmail->find(2);
									if($successmail['status']==1){
										$mail->Subject  = $successmail['title'];
										$body = str_replace('%username%', $_POST['sendusername'], $successmail['content']);
										$body = str_replace('%date%', date('Y-m-d H:i:s'), $body);

									}
								}
								$mail->MsgHTML($body);
								$mail->Send();
							}

						}

						$this->success('修改用户成功',  __APP__.'/User/index');
					}else{
						$this->error($user->getError());
					}

			}else{
				$this->error('异常操作');
			}

		}

		/**
		 * 删除用户
		 */
		function del(){
			if(!empty($_POST['actions'])){
				$srcdir = './Public/Content/User/';
				$user = M('User');
				$roleuser = M('RoleUser');
				foreach($_POST['actions'] as $key=>$value){
					$data = $user->find($value);
					if($data['username']=='admin'){
						$this->error('admin管理员不能被删除');
					}else{
						$num = $user->delete($value);
						$roleuser->where('userid='.$value)->delete();
						unlink($srcdir.$data['gravatar']);
					}
				}
				if($num>0){
					$this->success('删除用户成功');
				}else{
					$this->error('删除用户失败');
				}
			}else{
				$this->error('请选用用户');
			}
		}

	}